import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Stream;

/**
 * 类说明.
 *
 * @author weibo
 * @since 2018/9/5
 */
public abstract class AbsDocument implements Document {

    private Map<String, Object> properties;

    public AbsDocument(Map<String, Object> properties) {
        this.properties = properties;
    }

    @Override
    public Object get(String key) {
        return this.properties.get(key);
    }

    @Override
    public void put(String key, Object value) {
        this.properties.put(key, value);
    }

    @Override
    public <T> Stream<T> children(String key, Function<Map<String, Object>, T> construct) {
        Optional<List<Map<String, Object>>> optional
            = Stream.of(get(key)).filter(el -> el != null).map(es -> (List<Map<String, Object>>) es).findAny();
        return optional.isPresent() ? optional.get().stream().map(construct) : Stream.empty();
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append(getClass().getName()).append("[");
        properties.entrySet()
            .forEach(e -> builder.append("[").append(e.getKey()).append(" : ").append(e.getValue()).append("]"));
        builder.append("]");
        return builder.toString();
    }
}
